
function xml2str(xml) {
    return new XMLSerializer().serializeToString(xml);
}

const editorDiv = document.getElementById('editor');
const blocklyDiv = document.getElementById('blocklyDiv');
var workspace;
const gavascript = new Blockly.Generator('gavascript');
gavascript.blockToCode = function (a, b) {
    false === this.isInitialized && console.warn("Generator init was not called before blockToCode was called.");
    if (!a)
        return "";
    if (a.isInsertionMarker())
        return b ? "" : this.blockToCode(a.getChildren(false)[0]);
    let c = this[a.type];
    if ("function" != typeof c)
        throw Error(`"${this.name_}"语言不知道如何给块"${a.type}"生成代码`);
    c = c.call(a, a);
    if (Array.isArray(c)) {
        if (!a.outputConnection)
            throw TypeError("Expecting string from statement block: " + a.type);
        return [this.scrub_(a, c[0], b), c[1]];
    }
    if ("string" == typeof c)
        return this.STATEMENT_PREFIX && !a.suppressPrefixSuffix && (c = this.injectId(this.STATEMENT_PREFIX, a) + c), this.STATEMENT_SUFFIX && !a.suppressPrefixSuffix && (c += this.injectId(this.STATEMENT_SUFFIX, a)), this.scrub_(a, c, b);
    if (null === c)
        return "";
    throw SyntaxError("Invalid code generated: " + c);
}
const editor = CodeMirror(editorDiv, {
    lineNumbers: true,
    mode: 'javascript',
    theme: '3024-day',
    indentUnit: 4,
    value: 'Hi~ o(*￣▽￣*)ブ\n欢迎使用Glockly！',
    readOnly: true,
    lineWrapping: true
});
$.get("/toolbox.xml", function (data) {
    $.get("/blocks.json", function (data) {
        Blockly.defineBlocksWithJsonArray(data);
    });
    data = xml2str(data);
    workspace = Blockly.inject(blocklyDiv, {
        toolbox: data,
        media: '/media',
        renderer: 'codemao'
    });
    workspace.addChangeListener(updateCode);
});
const onresize = function () {
    blocklyDiv.style.width = (window.innerWidth - 500) + 'px';
    blocklyDiv.style.height = (window.innerHeight - 20) + 'px';
    editor.setSize('480px', (window.innerHeight - 20) + 'px');
};
function updateCode() {
    const code = gavascript.workspaceToCode(workspace);
    editor.setValue(code)
}
window.addEventListener('resize', onresize, false);
onresize();